//
//  EFengCreateDisDepartMentController.m
//  WZEfengAndEtong
//
//  Created by wanzhao on 16/1/21.
//  Copyright © 2016年 wanzhao. All rights reserved.
//

#import "EFengCreateDisDepartMentController.h"

#import "DepartMemberInfoCell.h"
#import "EFengOrgnizationSelectionCell.h"
#import "EFengMemberSelectionCell.h"
#import "CDepartmentMgr.h"
#import "CDepartmentModel.h"
#import "CContactMgr.h"
#import "CContactModel.h"
#import "UIImageView+WebCache.h"
#import "CXmppMgr.h"
#import "NSArray+PinYin.h"
#import "CXmppRequestMgr.h"
#import "CAccountModel.h"
#import "CFolderMgr.h"
#import "CServerSettingMgr.h"
#import "UIImage+ImageWithColor.h"
#import "IMSearchDisplayController.h"
#import "UIBarButtonItem+category.h"
#import "CPresenceModel.h"
#import "CPresenceMgr.h"
#import "EFengLatestContactSelectCell.h"
#import "UIImage+ImageWithColor.h"
#import "MBProgressHUD+WZ.h"
#import "CGroupModel.h"
#import "CHChatRoomBase.h"
#import "CGroupMemberMgr.h"
#import "CGroupMemberModel.h"
#import "CGroupMgr.h"
#import "CXmppMgr.h"
#import "MBProgressHUD+WZ.h"
#import "UIUtil.h"
#define KSECTIONHEIGHT 35.0f
#define KNORMALCELLHEIGHT 60.0f

@interface EFengCreateDisDepartMentController ()<UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, UISearchDisplayDelegate, EFengMemberSelectionCellDelegate, EFengOrgnizationSelectionCellDelegate, EFengLatestContactSelectCellDelegate>

{
    UITableView *_tableView;
    UISearchBar *_searchBar;
    UISearchDisplayController *_searchDisplayController;
    NSString *_departId;
    NSArray *_departList;
    NSArray *_contactList;
    CContactMgr *_contactMgr;
    CDepartmentMgr *_departMentMgr;
    NSMutableArray *_searchAllFirstLetter;
    NSMutableArray *_searchSectionListArray;
    NSInteger _contactNum;
    CPresenceMgr *_presenceMgr;
    CGroupMemberMgr *_groupMemMgr;
    CGroupMgr *_groupMgr;
    
}
StrongProperty NSMutableArray *subDepArray;
StrongProperty NSMutableArray *subMemberArray;
WeakProperty UIButton *bottomButton;
StrongProperty NSArray *selectedArray;
StrongProperty CContactModel *curUser;
StrongProperty NSMutableArray *depAllmemArray;
StrongProperty NSMutableArray *unSelectdepAllmemArray;

StrongProperty NSArray *groupMemberArray;
@end

@implementation EFengCreateDisDepartMentController



- (NSMutableArray *)unSelectdepAllmemArray
{
    if (_unSelectdepAllmemArray == nil) {
        _unSelectdepAllmemArray = [NSMutableArray array];
    }
    return _unSelectdepAllmemArray;
}
- (NSMutableArray *)depAllmemArray
{
    if (_depAllmemArray == nil) {
        _depAllmemArray = [NSMutableArray array];
    }
    return _depAllmemArray;
}


- (NSMutableArray *)subDepArray
{
    if (_subDepArray == nil) {
        _subDepArray = [NSMutableArray array];
    }
    return _subDepArray;
}

- (NSMutableArray *)subMemberArray
{
    if (_subMemberArray == nil) {
        _subMemberArray = [NSMutableArray array];
    }
    return _subMemberArray;
}
-(id)initWithDepartId:(NSString *)departId
{
    self = [super init];
    if(self)
    {
        _departId = departId;
    }
    return self;
}

- (void)dealloc
{
    
    //    NSLog(@"departDetailVC");
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPCREATEDISCUSSION object:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.selectedArray = [_contactMgr loadAllSelectedContact];
    if (self.selectedArray.count > 0) {
        [self.bottomButton setTitle:[NSString stringWithFormat:@"邀请(%zd)",self.selectedArray.count] forState:UIControlStateNormal];
        self.bottomButton.enabled = YES;
    } else {
        [self.bottomButton setTitle:@"邀请" forState:UIControlStateNormal];
        self.bottomButton.enabled = NO;
    }
    
    _departList = [_departMentMgr loadDepartments:_departId];
    
    __block BOOL isMember = NO;
    
    [_departList enumerateObjectsUsingBlock:^(CDepartmentModel *obj, NSUInteger idx, BOOL * stop) {
        [self.depAllmemArray removeAllObjects];
        [self.unSelectdepAllmemArray removeAllObjects];
        _contactNum = 0;
        [self loadAllSubDepMemWithDepId:obj.DEPTID];
        [self loadAllSelectedMemCountWithDepId:obj.DEPTID];
        [self.unSelectdepAllmemArray addObjectsFromArray:self.depAllmemArray];
        
        for (CContactModel *obj in self.depAllmemArray) {
            if ([obj.UserID isEqualToString:self.curUser.UserID]) {
                [self.unSelectdepAllmemArray removeObject:obj];
            }
            isMember = NO;
            for (CContactModel *contact in self.groupMemberArray) {
                if ([contact.UserID isEqualToString:obj.UserID]) {
                    isMember = YES;
                    [self.unSelectdepAllmemArray removeObject:obj];
                    break;
                }
            }
        }
        obj.UserNum = self.unSelectdepAllmemArray.count;
        if (obj.UserNum <= _contactNum && obj.UserNum > 0) {
            obj.isSelected = YES;
        } else {
            obj.isSelected = NO;
        }
    }];
    
    NSArray *array = [_contactMgr loadContactByDeptID:_departId];
    
    __block NSMutableArray *arrayM = [NSMutableArray array];
    [array enumerateObjectsUsingBlock:^(CContactModel *obj, NSUInteger idx, BOOL * stop) {
        isMember = NO;
        for (CContactModel *contact in self.groupMemberArray) {
            if ([obj.UserID isEqualToString:contact.UserID]) {
                isMember = YES;
                break;
            }
        }
        if (!isMember && ![obj.UserID isEqualToString:self.curUser.UserID]) {
            [arrayM addObject:obj];
        }
    }];
    
    _contactList = [NSArray sortArray:arrayM];
    [_tableView reloadData];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
    [self.navigationController setNavigationBarHidden:NO];
    [self.navigationItem setHidesBackButton:YES];
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:@"call_back" title:@"返回" target:self sel:@selector(backForPop) titleFont:Font18 titleColor:WhiteColor];
    if (IsIOS7) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(createSuccess:) name:K_XMPPCREATEDISCUSSION object:nil];
    _contactNum = 0;
    _departMentMgr = [[CDepartmentMgr alloc] init];
    CServerSettingModel *setting = [[CFolderMgr shareInstance].serSettingMgr getSetting];
    _departMentModel = [_departMentMgr loadDepartment:_departId];
    _contactMgr = [[CContactMgr alloc] init];
//    _departList = [_departMentMgr loadDepartments:_departId];
//    _contactList = [NSArray sortArray:[_contactMgr loadContactByDeptID:_departId]];
    _presenceMgr = [[CPresenceMgr alloc] init];
    _groupMgr = [[CGroupMgr alloc] init];
    _groupMemMgr = [[CGroupMemberMgr alloc] init];
    
    if (_departMentModel == nil) {
        [self.navigationItem setNewTitleCenter:[NSString stringWithFormat:@"%@",setting.companyName]];
    } else {
        if (_departMentModel.DepartName.length > 0) {
            [self.navigationItem setNewTitleCenter:[NSString stringWithFormat:@"%@",_departMentModel.DepartName]];
        } else {
            [self.navigationItem setNewTitleCenter:[NSString stringWithFormat:@"%@",setting.companyName]];
        }
        
    }

    
    //加载我的父部门信息
    CAccountModel *model = [[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount];
    self.curUser = [[[CContactMgr alloc] init] loadContactWithUserCode:model.userName];
    
     self.navigationItem.rightBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:nil title:@"取消" target:self sel:@selector(cancel) titleFont:Font18 titleColor:WhiteColor];
    
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 44.0f, HARDWARE_SCREEN_WIDTH, HARDWARE_SCREEN_HEIGHT - 64 - 44.0f - 90.0f) style:UITableViewStyleGrouped];
    _tableView.frame = CGRectMake(0, 44.0f, HARDWARE_SCREEN_WIDTH, HARDWARE_SCREEN_HEIGHT - 64 - 44.0f - 90.0f);
    _tableView.sectionIndexColor = RGBCOLOR(0x64, 0x64, 0x64);
    _tableView.sectionIndexBackgroundColor = ClearColor;
    _tableView.sectionIndexTrackingBackgroundColor = ClearColor;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    _tableView.backgroundColor = [UIColor clearColor];
    _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
    _searchBar.backgroundImage = [UIImage strechingWithImageName:@"BG-search"];
    //test 研发中心搜素
    _searchBar.placeholder = @"搜索";
    _searchBar.delegate = self;
    // 添加 searchbar 到 headerview
    [self.view addSubview:_searchBar];
    
    _searchDisplayController = [[IMSearchDisplayController alloc] initWithSearchBar:_searchBar contentsController:self];
    
    // searchResultsDataSource 就是 UITableViewDataSource
    _searchDisplayController.searchResultsDataSource = self;
    // searchResultsDelegate 就是 UITableViewDelegate
    _searchDisplayController.searchResultsDelegate = self;
    _searchDisplayController.delegate = self;
    _searchDisplayController.searchResultsTableView.sectionIndexColor = RGBCOLOR(0x64, 0x64, 0x64);
    _searchDisplayController.searchResultsTableView.sectionIndexBackgroundColor = ClearColor;
    _searchDisplayController.searchResultsTableView.sectionIndexTrackingBackgroundColor = ClearColor;
    
    self.view.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    _searchAllFirstLetter = [NSMutableArray arrayWithCapacity:5];
    _searchSectionListArray = [NSMutableArray arrayWithCapacity:5];
    
    
    
    UIButton *bottomButton = [UIButton buttonWithType:UIButtonTypeCustom];
    bottomButton.layer.cornerRadius = 3.0f;
    bottomButton.layer.masksToBounds = YES;
    [bottomButton setTitleColor:WhiteColor forState:UIControlStateNormal];
    [bottomButton addTarget:self action:@selector(createDiscussList) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:bottomButton];
   bottomButton.frame = CGRectMake(10.0f, HARDWARE_SCREEN_HEIGHT - 64.0f - 40.0f - 25.0f, HARDWARE_SCREEN_WIDTH - 20.0f, 40.0f);
    [bottomButton setBackgroundImage:[UIImage createImageWithColor:RGBCOLOR(89, 136, 243) withBounds:bottomButton.bounds] forState:UIControlStateNormal];
    self.bottomButton = bottomButton;

    
    if (self.group) {
        NSArray *array = [_groupMemMgr loadAllGroupMemberByGroupID:self.group.GroupId];
        NSMutableArray *arrayM = [NSMutableArray array];
        for (CGroupMemberModel *groupModel in array) {
            CContactModel *contact = [_contactMgr loadContactWithUserId:groupModel.UserId];
            if (contact) {
                if (contact.isDel == 1) {
                    [arrayM addObject:contact];
                } else {
                    [_groupMemMgr delGroupMember:groupModel];
                }
            }
        }
        self.group.UserNum = arrayM.count;
        [_groupMgr updateGroup:self.group];
        self.groupMemberArray = arrayM;
    }

}
//bug 8670 fixed by lixu
-(void)createSuccess:(NSNotification*)notification
{
    [UIUtil hideMBProgressViewForView:self.view];
    [self dismissViewControllerAnimated:NO completion:^{
        CHChatRoomBase *chat = [[CHChatRoomBase alloc] init];
        chat.member = nil;
        NSString *groupID = notification.userInfo[@"groupid"];
        //bug 9270 fixed by lixu
        chat.group = [[[CGroupMgr alloc]init]loadGroup:groupID];
        UINavigationController *rotNav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        UIViewController *vc = rotNav.childViewControllers[1];
        [rotNav popToViewController:vc animated:NO];
        
        [rotNav pushViewController:chat animated:YES];
        
    }];
}
//bug 8670 fixed by lixu
- (void)createDiscussList
{
    
    if ([CXmppMgr shareInstance].reachability.currentReachabilityStatus == NotReachable) {
        [MBProgressHUD showError:@"网络异常"];
        return;
    }

    if (self.group == nil) {
        if (self.selectedArray.count > 1) {
            CGroupModel *group = [[CGroupModel alloc] init];
            group.isShow = NO;
            group.groupType = 1;
            NSMutableString *groupName = [NSMutableString string];
            for (CContactModel *contact in self.selectedArray) {
                
                [groupName appendFormat:@"%@,",contact.UserName];
            }
            
            [groupName appendString:self.curUser.UserName];
            
            group.GroupName = groupName;
            group.GroupNotice = self.curUser.UserName;
            group.GroupIntroduction = self.curUser.UserName;
            [[CXmppRequestMgr shareInstance] creatDiscussWithGroup:group curUser:self.curUser];
            [UIUtil addMBProgressViewTitle:@"创建中..." inView:self.view alpha:1 failureTitle:@"创建失败"];
//            [self cancel];
            
        } else if (self.selectedArray.count == 1) {
            
            [self dismissViewControllerAnimated:NO completion:^{
                CContactModel *contact = self.selectedArray.lastObject;
                CHChatRoomBase *chat = [[CHChatRoomBase alloc] init];
                chat.member = contact;
                chat.group = nil;
                
                UINavigationController *rotNav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                UIViewController *vc = rotNav.childViewControllers[1];
                [rotNav popToViewController:vc animated:NO];
                
                [rotNav pushViewController:chat animated:YES];
                
            }];
            
        }
        
    } else {
        NSInteger memCount = self.group.UserNum + self.selectedArray.count;
        if (memCount > 50) {
            [MBProgressHUD showError:@"已达50人上限"];
            return;
        } else {
            
            [[CXmppRequestMgr shareInstance] addDiscussMemberwithGroup:self.group members:self.selectedArray curUser:nil];
            [self cancel];
            
        }
    }
}

- (void)backForPop
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)cancel
{
    [self dismissViewControllerAnimated:YES completion:nil];
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */


#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if(tableView == _tableView)
    {
        NSInteger rows = 0;
        switch (section) {
            case 0:
                if([_departList count] > 0)
                {
                    rows = [_departList count];
                }
                else
                {
                    rows = [_contactList count];
                }
                break;
            case 1:
                rows = [_contactList count];
                break;
            default:
                rows = 0;
                break;
        }
        return rows;
    }
    else
    {
        NSArray *rowArray = _searchSectionListArray[section];
        return [rowArray count];
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView              // Default is 1 if not implemented
{
    if(tableView == _tableView)
    {
        NSInteger section = 0;
        if([_departList count] > 0)
        {
            section ++;
        }
        if([_contactList count] > 0)
        {
            section ++;
        }
        
        return section;
    }
    else
    {
        return _searchSectionListArray.count;
    }
}
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView == _tableView)
    {
        UITableViewCell *cell = nil;
        if(indexPath.section == 0 && [_departList count] > 0)
        {
            EFengOrgnizationSelectionCell *departCell = [EFengOrgnizationSelectionCell eFengOrgnizationSelectionCellWithTableView:tableView];
            departCell.orgnizationDelegate = self;
            departCell.cellIndexPath = indexPath;
            departCell.tableView = tableView;
            
            [departCell.departIcon  setImage:[UIImage imageNamed:@"icon-Group"] forState:UIControlStateNormal];
            CDepartmentModel *departModel = [_departList objectAtIndex:indexPath.row];
            [departCell.departNameLabel setText:departModel.DepartName];
            
            
            //  bug 6106 fixed by 荣则兵
            [departCell.departCountLabel setText:@""];
            
//            if (departModel.UserNum > 0) {
//                
//                [departCell.departCountLabel setText:[NSString stringWithFormat:@"%zd", departModel.UserNum]];
//                
//            } else {
//            }

            
            if(indexPath.section == 0 && indexPath.row == _departList.count - 1)
            {
                [departCell.seperatorLine setHidden:YES];
            }
            else
            {
                [departCell.seperatorLine setHidden:NO];
            }
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell = departCell;
            
            departCell.selectIcon.selected = departModel.isSelected;
            }
        else
        {
            EFengMemberSelectionCell *departMemberCell = [EFengMemberSelectionCell eFengMemberSelectionCellWithTableView:tableView];
            departMemberCell.tableView = tableView;
            departMemberCell.eFengMemberSelectionCellDelegate = self;
            departMemberCell.cellIndexPath = indexPath;
            
            CContactModel *contactModel = [_contactList objectAtIndex:indexPath.row];
            CPresenceModel *presence = [_presenceMgr getPresenceWithUserCode:contactModel.UserCode];
            if (presence) {
                if ([presence.IsAvailable isEqualToString:@"在线"] || [presence.pcAvailable isEqualToString:@"在线"]) {
                    if ([contactModel.SEX isEqualToString:@"女"]) {
                        
                        [departMemberCell.sexIcon setImage:[UIImage imageNamed:@"icon-woman"] forState:UIControlStateNormal];
                    } else {
                        [departMemberCell.sexIcon setImage:[UIImage imageNamed:@"icon-man"] forState:UIControlStateNormal];
                    }
                    
                } else {
                    if ([contactModel.SEX isEqualToString:@"女"]) {
                        
                        [departMemberCell.sexIcon setImage:[UIImage imageNamed:@"icon-womanOffline"] forState:UIControlStateNormal];
                    } else {
                        [departMemberCell.sexIcon setImage:[UIImage imageNamed:@"icon-manOffline"] forState:UIControlStateNormal];
                    }
                    
                    
                }
                
            } else {
                if ([contactModel.SEX isEqualToString:@"女"]) {
                    
                    [departMemberCell.sexIcon setImage:[UIImage imageNamed:@"icon-womanOffline"] forState:UIControlStateNormal];
                } else {
                    [departMemberCell.sexIcon setImage:[UIImage imageNamed:@"icon-manOffline"] forState:UIControlStateNormal];
                }
                
            }
            
            [departMemberCell.userNameLabel setText:contactModel.UserName];
            
            [departMemberCell.positionLabel setText:contactModel.Position];
            if(indexPath.row == _contactList.count - 1)
            {
                [departMemberCell.seperatorLine setHidden:YES];
            }
            else
            {
                [departMemberCell.seperatorLine setHidden:NO];
            }
            
            departMemberCell.selectIcon.selected = contactModel.isSelected;
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell = departMemberCell;
        }
        return cell;
    }
    else
    {
        NSArray *rowArray = _searchSectionListArray[indexPath.section];
        CContactModel *contact = rowArray[indexPath.row];
        
        EFengLatestContactSelectCell *groupMemberCell = [EFengLatestContactSelectCell eFengLatestContactSelectCellWithTableview:tableView];
        groupMemberCell.eFengLatestContactSelectCellDelegate = self;
        groupMemberCell.cellIndexPath = indexPath;
        groupMemberCell.tableView = tableView;
        
        [groupMemberCell.headerIcon sd_setImageWithURL:[NSURL URLWithString:[[CXmppRequestMgr shareInstance] DownHeadFileWithContact:contact.UserID]] placeholderImage:[UIImage imageNamed:@"80-80"]];
        //        [groupMemberCell.titleLabel setText:@"测试名字"];
        [groupMemberCell.userNameLabel setText:contact.UserName];
        NSInteger rows = [tableView numberOfRowsInSection:indexPath.section];
        if(indexPath.row == rows - 1)
        {
            [groupMemberCell.seperatorLine setHidden:NO];
            groupMemberCell.shortLine.hidden = YES;
        } else {
            groupMemberCell.seperatorLine.hidden = YES;
            groupMemberCell.shortLine.hidden = NO;
        }
        groupMemberCell.selectIcon.selected = contact.isSelected;
        return groupMemberCell;
    }
}




#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (_tableView == tableView) {
        CGFloat height = 0.01f;
        switch (section) {
            case 0:
                height = KSECTIONHEIGHT;
                break;
            case 1:
                height = KSECTIONHEIGHT;
                break;
            default:
                height = KSECTIONHEIGHT;
                break;
        }
        return height;
    }
    
    
    return KSECTIONHEIGHT;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    CGFloat height = 0.01f;
    //    switch (section) {
    //        case 1:
    //            height = 2;
    //            break;
    //        default:
    //            break;
    //    }
    return height;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (_tableView == tableView) {
        return nil;
    } else{
        return _searchAllFirstLetter;
    }
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    NSInteger count = 0;
    if(tableView == _tableView)
    {
        count = index;
    } else {
        count = index;
    }
    return count;
}




- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section   // custom view for header. will be adjusted to default or specified header height
{
    UIView *headerView = nil;
    //    if(section == 0)
    //    {
    //        return headerView;
    //    }
    headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, tableView.frame.size.width, KSECTIONHEIGHT);
    headerView.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    UIView *beginLine = [[UIView alloc] init];
    beginLine.frame = CGRectMake(0, 0, tableView.frame.size.width, 0.5);
    [beginLine setBackgroundColor:KSEPERATORLINECOLOR];
    [headerView addSubview:beginLine];
    
    UIView *endLine = [[UIView alloc] init];
    endLine.frame = CGRectMake(0, KSECTIONHEIGHT-0.5, tableView.frame.size.width, 0.5);
    [endLine setBackgroundColor:KSEPERATORLINECOLOR];
    [headerView addSubview:endLine];
    
    UILabel *label = [[UILabel alloc] init];
    if (_tableView == tableView) {
        if(section == 0 && [_departList count] > 0)
        {
            [label setText:@"组织"];
        }
        else
        {
            [label setText:@"成员"];
        }
        
    } else {
        label.text = _searchAllFirstLetter[section];
    }
    [label setTextColor:RGBCOLOR(0x92, 0x92, 0x92)];
    label.frame = CGRectMake(15, 1, 200, KSECTIONHEIGHT-2);
    [headerView addSubview:label];
    
    return headerView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section   // custom view for footer. will be adjusted to default or specified footer height
{
    UIView *headerView = nil;
    //    if(section != 1 && [_contactList count] > 0)
    //    {
    //        return headerView;
    //    }
    //    if(section == 0 && [_departList count] > 0)
    //    {
    //        return headerView;
    //    }
    //
    //    headerView = [[UIView alloc] init];
    //    headerView.frame = CGRectMake(0, 0, tableView.frame.size.width, 2);
    //    headerView.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    //    UIView *beginLine = [[UIView alloc] init];
    //    beginLine.frame = CGRectMake(0, 0, tableView.frame.size.width, 0.5);
    //    [beginLine setBackgroundColor:KSEPERATORLINECOLOR];
    //    [headerView addSubview:beginLine];
    return headerView;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = KNORMALCELLHEIGHT;
    
    if(indexPath.row == 0 && indexPath.section == 0)
    {
        height = KNORMALCELLHEIGHT;
    }
    return height;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (_tableView == tableView) {
        
        switch (indexPath.section) {
            case 0:
            {
                if (_departList.count > 0) {
                    CDepartmentModel *departModel = [_departList objectAtIndex:indexPath.row];
                    [self showDepartDetailVC:departModel.DEPTID];
                } else {
                   
                }
            }
                break;
                
                
            case 1:
            {
               
            }
                break;
                
            default:
                break;
        }
    } else {
        
    }
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 1)
    {
        return UITableViewCellEditingStyleDelete;
    }
    return UITableViewCellEditingStyleNone;
}
//- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
//{
//
//}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return NO;
}
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(3_0)
{
    return @"删除";
}




-(void)showDepartDetailVC:(NSString *)currentDepartId
{
    EFengCreateDisDepartMentController *departDetail = [[EFengCreateDisDepartMentController alloc] initWithDepartId:currentDepartId];
    departDetail.group = self.group;
    //    CHSNavigationController *departDetailNav = [[CHSNavigationController alloc] initWithRootViewController:departDetail];
    //    [self.leveyTabBarController presentViewController:departDetailNav animated:YES completion:nil];
    [self.navigationController pushViewController:departDetail animated:YES];
    
}




- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [_searchSectionListArray removeAllObjects];
    [_searchAllFirstLetter removeAllObjects];
    NSArray *contactArray = [_contactMgr searchContactWithSeachStr:searchText];
    if (contactArray == nil) {
        return;
    }
    NSMutableArray *arrayM = [NSMutableArray array];
    __block BOOL isMem = NO;
    [contactArray enumerateObjectsUsingBlock:^(CContactModel *obj, NSUInteger idx, BOOL * stop) {
        isMem = NO;
        
        for (CContactModel *contact in self.groupMemberArray) {
            
            if ([obj.UserID isEqualToString:contact.UserID]) {
                isMem = YES;
                break;
            }
        }
        if (!isMem && ![obj. UserID isEqualToString:self.curUser.UserID]) {
            [arrayM addObject:obj];
        }
    }];
    _searchAllFirstLetter = [NSArray IndexArray:arrayM];
    _searchSectionListArray = [NSArray LetterSortArray:arrayM];
    
    
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
// called when text starts editing
{
    searchBar.showsCancelButton = YES;
    for(id cc in [_searchDisplayController.searchBar subviews])
    {
        if([cc isKindOfClass:[UIButton class]])
        {
            UIButton *btn = (UIButton *)cc;
            [btn setTitle:@"取消"  forState:UIControlStateNormal];
        }
    }
    
}

//隐藏搜索为空时cell的分割线
//bug 8510 fixed by lixu
- (void)searchDisplayController:(UISearchDisplayController *)controller willShowSearchResultsTableView:(UITableView *)tableView NS_DEPRECATED_IOS(3_0,8_0){
    [tableView setContentInset:UIEdgeInsetsZero];
    [tableView setScrollIndicatorInsets:UIEdgeInsetsZero];
    tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
}

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString

{ for(UIView *subview in controller.searchResultsTableView.subviews) {
    
    if([subview isKindOfClass:[UILabel class]]) {
        
        [(UILabel*)subview setText:@"未找到匹配的信息"];
        
    }
    
}
    return YES;
}


- (void) searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller NS_DEPRECATED_IOS(3_0,8_0)
{
    UIView *topView = controller.searchBar.subviews[0];
    
    for (UIView *subView in topView.subviews) {
        
        if ([subView isKindOfClass:NSClassFromString(@"UINavigationButton")]) {
            
            UIButton * cancelButton = (UIButton*)subView;
            
            [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
            
        }
        
    }
}


#pragma mark cellde 代理方法
- (void)eFengLatestContactSelectCellDidselectWithIndexPath:(NSIndexPath *)indexPath tableView:(UITableView *)tableView
{
    NSArray *rowArray = _searchSectionListArray[indexPath.section];
    CContactModel *contact = rowArray[indexPath.row];
    

    if (!contact.isSelected) {
        NSInteger memCount = 0;
        memCount = self.groupMemberArray.count + self.selectedArray.count;
        if (memCount >= 50) {
            [MBProgressHUD showError:@"已达50人上限"];
            return;
        }

    }
    contact.isSelected = !contact.isSelected;
    
    [_contactMgr updateContactSelectedWithContact:contact seleceted:contact.isSelected];
    [_searchDisplayController.searchResultsTableView reloadData];
  
    self.selectedArray = [_contactMgr loadAllSelectedContact];
    
    
    if (self.selectedArray.count > 0) {
        [self.bottomButton setTitle:[NSString stringWithFormat:@"邀请(%zd)",self.selectedArray.count] forState:UIControlStateNormal];
        self.bottomButton.enabled = YES;
    } else {
        [self.bottomButton setTitle:@"邀请" forState:UIControlStateNormal];
        self.bottomButton.enabled = NO;
    }


}
- (void)eFengMemberSelectionCellDidSelecWithIndexPath:(NSIndexPath *)indexPath tableView:(UITableView *)tableView
{
    CContactModel *contact = _contactList[indexPath.row];
    
    if (!contact.isSelected) {
        NSInteger memCount = 0;
        memCount = self.groupMemberArray.count + self.selectedArray.count;
        if (memCount >= 50) {
            [MBProgressHUD showError:@"已达50人上限"];
            return;
        }
    }
    
   contact.isSelected = !contact.isSelected;
    
    [_contactMgr updateContactSelectedWithContact:contact seleceted:contact.isSelected];
    [_tableView reloadData];

   self.selectedArray = [_contactMgr loadAllSelectedContact];
    if (self.selectedArray.count > 0) {
        [self.bottomButton setTitle:[NSString stringWithFormat:@"邀请(%zd)",self.selectedArray.count] forState:UIControlStateNormal];
        self.bottomButton.enabled = YES;
    } else {
        [self.bottomButton setTitle:@"邀请" forState:UIControlStateNormal];
        self.bottomButton.enabled = NO;
    }

}

- (void)EFengOrgnizationSelectionCellDidSelectWithIndexPath:(NSIndexPath *)indexPath tableView:(UITableView *)tableView
{
   
    
    __block CDepartmentModel *dep = _departList[indexPath.row];
    
    
    
    if (!dep.isSelected) {
        NSInteger memCount = 0;
        memCount = self.groupMemberArray.count + self.selectedArray.count + dep.UserNum;
        if (memCount > 50) {
            [MBProgressHUD showError:@"已达50人上限"];
            return;
        }
    }
   
    dep.isSelected = !dep.isSelected;
    [self.subMemberArray removeAllObjects];
    [self.subDepArray removeAllObjects];
    [self.unSelectdepAllmemArray removeAllObjects];
    [self loadAllSubdDepAndMemberWithDep:dep];
    [self.unSelectdepAllmemArray addObjectsFromArray:self.subMemberArray];
    BOOL isMember = NO;
    for (CContactModel *obj in self.subMemberArray) {
        if ([obj.UserID isEqualToString:self.curUser.UserID]) {
            [self.unSelectdepAllmemArray removeObject:obj];
        }
        isMember = NO;
        for (CContactModel *contact in self.groupMemberArray) {
            if ([contact.UserID isEqualToString:obj.UserID]) {
                isMember = YES;
                [self.unSelectdepAllmemArray removeObject:obj];
                break;
            }
        }
    }

    
    
    [_contactMgr updateSelectWithContactList:self.unSelectdepAllmemArray isSelected:dep.isSelected];
    [_departMentMgr updateSelectWithDeptList:self.subDepArray isSelected:dep.isSelected];
    
    [_departMentMgr updateDeptSelectedWithDept:dep seleceted:dep.isSelected];
    [_tableView reloadData];
    
    self.selectedArray = [_contactMgr loadAllSelectedContact];
    if (self.selectedArray.count > 0) {
        [self.bottomButton setTitle:[NSString stringWithFormat:@"邀请(%zd)",self.selectedArray.count] forState:UIControlStateNormal];
        self.bottomButton.enabled = YES;
    } else {
        [self.bottomButton setTitle:@"邀请" forState:UIControlStateNormal];
        self.bottomButton.enabled = NO;
    }

}

- (void)loadAllSubdDepAndMemberWithDep:(CDepartmentModel *)dep
{
    NSArray *depArray = [_departMentMgr loadDepartments:dep.DEPTID];
    [self.subDepArray addObjectsFromArray:depArray];
    NSArray *contactArray = [_contactMgr loadContactByDeptID:dep.DEPTID];
    [self.subMemberArray addObjectsFromArray:contactArray];
    
    for (CDepartmentModel *dep in depArray) {
        [self loadAllSubdDepAndMemberWithDep:dep];
    }
}

- (void)loadAllSubDepMemWithDepId:(NSString *)depId
{
    
    NSArray *array = [_contactMgr loadContactUserIdAndDepIdByDeptID:depId];
    [self.depAllmemArray addObjectsFromArray:array];
    NSArray *depArray = [_departMentMgr loadDepartments:depId];
    for (CDepartmentModel *depModel in depArray) {
        [self loadAllSubDepMemWithDepId:depModel.DEPTID];
    }
}

- (NSInteger)loadAllSelectedMemCountWithDepId:(NSString *)depId
{
    _contactNum = _contactNum + [_contactMgr loadAllSelectedCountContactWithDepId:depId];
    NSArray *array = [_departMentMgr loadDepartments:depId];
    for (CDepartmentModel *depModel in array) {
        [self loadAllSelectedMemCountWithDepId:depModel.DEPTID];
    }
    return _contactNum;

}
@end
